#include "updater.h"

Updater::Updater(QObject *parent) : QObject(parent)
  , m_manager(new QNetworkAccessManager(parent))
  , m_updateTempFile(new QFile)
{
    m_serverAddress = taskItem::config->m_serverAddress;
    m_check_url = m_serverAddress.endsWith("/")? m_serverAddress + "c_app/newest_version": m_serverAddress + "/c_app/newest_version";
    m_download_url = m_serverAddress.endsWith("/")? m_serverAddress + "c_app/downloadFile": m_serverAddress + "/c_app/downloadFile";
}

Updater::~Updater()
{
    delete this;
}

void Updater::checkVersion(QWidget *parent, QString version)
{
    m_serverAddress = taskItem::config->m_serverAddress;
    m_check_url = m_serverAddress.endsWith("/")? m_serverAddress + "c_app/newest_version": m_serverAddress + "/c_app/newest_version";
    m_download_url = m_serverAddress.endsWith("/")? m_serverAddress + "c_app/downloadFile": m_serverAddress + "/c_app/downloadFile";
    if (m_serverAddress.isEmpty())
    {
        QMessageBox::warning(parent, "错误", "服务器地址不能为空!", "确定");
        return ;
    }

    m_program = QApplication::applicationDirPath() + "/updater.exe";


    QNetworkRequest request;
    request.setUrl(QUrl(m_check_url));
    request.setRawHeader(QByteArray("User-Agent"), QByteArray("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36"));

    QNetworkReply *reply = m_manager->get(request);

    connect(reply, &QNetworkReply::readyRead, [=](){
        qDebug() << "readyRead ";
        this->m_html = reply->readAll();
    });
    connect(reply, &QNetworkReply::finished, [=](){
        if (reply->error() != QNetworkReply::NoError)
        {
            QMessageBox::warning(parent, "检查更新", "与服务器连接失败!","确定");
            return;
        }
        this->m_jsonDoc = QJsonDocument::fromJson(this->m_html);
        qDebug() << "html " << this->m_html;
//        QJsonArray jsonArr = jsonDoc.array();
//        QJsonObject jsonObj = jsonArr.at(0).toObject();
        QJsonObject jsonObj = m_jsonDoc.object();
        qDebug() << "json obj " << jsonObj;
        this->m_new_version = jsonObj.value("version").toString();
        this->m_new_describe = jsonObj.value("describe").toString();
        this->m_new_datetime = jsonObj.value("datetime").toString();

        qDebug() << "new version " << this->m_new_version << " new describe " << this->m_new_describe << " new datetime " << this->m_new_datetime;
        if (isNewest(version))
        {
            QMessageBox::information(parent, "检查更新", QString("当前已是最新版本"),"确定");

        } else
        {
            int ret = QMessageBox::information(parent, "检查更新", QString("是否更新至版本 %1(%2)\n新版特性:\n%3").arg(this->m_new_version).arg(this->m_new_datetime).arg(this->m_new_describe),"确定", "取消");
            qDebug() << "ret " << ret;
            if (ret ==0)
            {
                qDebug() << "prepare to download";
                if (!QFile::exists(m_program))
                {
                    QMessageBox::warning(parent, "错误", "未找到对应的更新程序", "确定");
                    return;
                }
                startUpdateProcess();
            }

        }


    });
}

bool Updater::isNewest(QString version)
{
    qDebug() << "version "<<version << " new version "  << m_new_version;
//    if (version >= m_new_version) return true;
    if (version.compare(m_new_version) >= 0 ) return true;
    return false;
}

void Updater::startUpdateProcess()
{
    QProcess *updateProcess = new QProcess;
    connect(updateProcess,&QProcess::started,[=](){
        QApplication::quit();
    });

    QStringList args;
    args << m_serverAddress << QString("%1").arg(QApplication::applicationName()) <<this->m_new_version << this->m_new_describe;
    updateProcess->start(m_program, args);
}
